package com.wind.sqlite.oauth2;

import com.wind.sqlite.entity.SysUserEntity;
import com.wind.sqlite.entity.SysUserTokenEntity;
import com.wind.sqlite.service.SysUserService;
import com.wind.sqlite.service.SysUserTokenService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OAuth2Realm extends AuthorizingRealm {
    @Autowired
    private SysUserTokenService sysUserTokenService;
    @Autowired
    private SysUserService sysUserService;

    public OAuth2Realm() {
    }

    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUserEntity user = (SysUserEntity)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String)token.getPrincipal();
        SysUserTokenEntity tokenEntity = this.sysUserTokenService.queryByToken(accessToken);
        if (tokenEntity != null && tokenEntity.getExpireTime().getTime() >= System.currentTimeMillis()) {
            SysUserEntity user = (SysUserEntity)this.sysUserService.getById(tokenEntity.getUserId());
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, this.getName());
            return info;
        } else {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
    }
}